package nero.yncc.com.createart.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapterShopCarOutSize;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.AddressBean;
import nero.yncc.com.createart.bean.BeanShopCar;
import nero.yncc.com.createart.bean.BeanWuliu;
import nero.yncc.com.createart.interfaces.InterfaceDoSomeThing;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.TextUtil;
import nero.yncc.com.createart.utils.TimeUtils;

/**
 * Created by nero on 2017/7/11.
 */

@ContentView(R.layout.activity_order_write)
public class ActivityOrderWrite extends BaseActivity {
    @ViewInject(R.id.tv_name)
    TextView tv_name;
    @ViewInject(R.id.tv_address)
    TextView tv_address;
    @ViewInject(R.id.tv_phone)
    TextView tv_phone;
    @ViewInject(R.id.tv_default)
    TextView tv_default;
    @ViewInject(R.id.ll_address)
    LinearLayout ll_address;
    @ViewInject(R.id.et_remark)
    EditText et_remark;  //备注信息
    @ViewInject(R.id.ll_sendTime)
    LinearLayout ll_sendTime; //发货时间选择
    @ViewInject(R.id.tv_sendtime)
    TextView tv_sendtime;
    @ViewInject(R.id.tv_all_money)
    TextView tv_all_money;//商品总金额
    @ViewInject(R.id.tv_sendMoney)
    TextView tv_sendMoney;//运费
    @ViewInject(R.id.rc_list)
    RecyclerView rc_list;
    @ViewInject(R.id.tv_allnum)
    TextView tv_allnum;//共多少件
    @ViewInject(R.id.tv_money)
    TextView tv_money;
    @ViewInject(R.id.tv_pay)
    TextView tv_pay;
    @ViewInject(R.id.tv_noaddress)
    TextView tv_noaddress;

    ArrayList<BeanShopCar> arrayList_shop;
    int allNum;
    double all_price;
    String ids;
    AdapterShopCarOutSize adapterShopCar;
    //地址管理
    ArrayList<AddressBean> arrayList_address;

    //物流
    ArrayList<BeanWuliu> arrayList_wuliu;
    String yunfei;
    @Override
    protected void initView() {
        super.initView();
        setTitleBarTitle("填写订单");
    }

    @Override
    protected void initData() {
        super.initData();
        arrayList_wuliu = new ArrayList<>();
        arrayList_address = new ArrayList<>();

        arrayList_shop = (ArrayList<BeanShopCar>) getIntent().getSerializableExtra("array");
        all_price = getIntent().getDoubleExtra("price", 0);
        allNum = getIntent().getIntExtra("count", 0);
        ids=getIntent().getStringExtra("ids");
        tv_money.setText("实付：￥" + all_price);
        tv_all_money.setText("￥" + all_price);
        tv_allnum.setText("共" + allNum + "件商品");

        adapterShopCar=new AdapterShopCarOutSize(this,this,arrayList_shop,userBean,false,new InterfaceDoSomeThing(){

        });
        rc_list.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        rc_list.setAdapter(adapterShopCar);
    }

    @Override
    protected void initListener() {
        super.initListener();
        tv_noaddress.setOnClickListener(this);
        ll_address.setOnClickListener(this);
        ll_sendTime.setOnClickListener(this);
        tv_pay.setOnClickListener(this);
    }

    private static final int REQUEST_ADDRESS_ADD = 0, REQUEST_ADDRESS_CHOOSE = 1;

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.tv_noaddress:
                //打开收货地址页面进行添加
                Intent intent = new Intent(mContext, ActivityAddressManager.class);
                intent.putExtra("canClick", true);
                startActivityForResult(intent, REQUEST_ADDRESS_ADD);
                break;
            case R.id.ll_address:
                //打开页面进行选择
                Intent intent2 = new Intent(mContext, ActivityAddressManager.class);
                intent2.putExtra("canClick", true);
                startActivityForResult(intent2, REQUEST_ADDRESS_CHOOSE);
                break;
            case R.id.ll_sendTime:
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        tv_sendtime.setText(TimeUtils.getDate(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false}).setDate(Calendar.getInstance())
                        .build();
                pvTime.show();
                break;
            case R.id.tv_pay:
                submitOrder();
                break;
        }
    }

    @Override
    protected void getHttpData() {
        super.getHttpData();
        //获取地址

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("user_id", userBean.getUser_id());
        new HttpUtils().post(this, Constants.API_ADDRESSLIST, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = (JSONArray) json;
                for (int a = 0; a < jsonArray.length(); a++) {
                    try {
                        arrayList_address.add(JSON.parseObject(jsonArray.getString(a), AddressBean.class));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                //如果没有收货地址 隐藏需要添加
                if (arrayList_address.size() == 0) {
                    tv_noaddress.setVisibility(View.VISIBLE);
                    ll_address.setVisibility(View.GONE);
                } else {
                    //分析那个是默认的
                    for (AddressBean addressBean_cache : arrayList_address) {
                        if (addressBean_cache.getIs_default().equals("1")) {
                            //是默认的
                            addressBean = addressBean_cache;
                            setAddressView();
                        }
                    }
                }

                getWuliu();
                hideProgress();
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                hideProgress();
            }
        });
    }

    AddressBean addressBean;
    BeanWuliu beanWuliu;
    private void setAddressView() {
        if (addressBean == null) return;
        tv_name.setText(TextUtil.getText(addressBean.getConsignee(), "未设置名称"));
        tv_phone.setText(TextUtil.getText(addressBean.getMobile(), "未填写电话"));
        tv_address.setText(addressBean.getProvince() + " " + addressBean.getCity() + "" + addressBean.getDistrict() + "" + addressBean.getAddress());
    }

    private void getWuliu() {
        HashMap<String, String> hashMap = new HashMap<>();
        new HttpUtils().post(this, Constants.API_WULIU, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = (JSONArray) json;
                for (int a = 0; a < jsonArray.length(); a++) {
                    try {
                        arrayList_wuliu.add(JSON.parseObject(jsonArray.getString(a), BeanWuliu.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (arrayList_wuliu.size() > 0)
                    beanWuliu=arrayList_wuliu.get(0);
                    getYunei(beanWuliu.getCode());
            }

            @Override
            public void fail(String failMsg) {

            }
        });

    }

    int weight = 10;

    private void getYunei(String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("shipping_code", code);
        hashMap.put("province", addressBean.getProvinceid());
        hashMap.put("city", addressBean.getCityid());
        hashMap.put("district", addressBean.getDistrictid());
        hashMap.put("weight", weight + "");
        new HttpUtils().post(this, Constants.API_YUNFEI, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                yunfei=json.toString();
                tv_sendMoney.setText("￥"+json.toString());
                tv_money.setText((Double.parseDouble(json.toString())+all_price)+"");
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg + ",请检查网络");
            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ADDRESS_ADD:
            case REQUEST_ADDRESS_CHOOSE:
                if (resultCode == RESULT_OK) {
                    addressBean = (AddressBean) data.getSerializableExtra("bean");
                    setAddressView();
                }
                break;
        }
    }

    private void getOrderWeight(){

    }

    private void submitOrder(){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("cart_id", ids);
        new HttpUtils().post(this, Constants.API_JIAOYAN, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                if (msg.equals("库存校验成功")) {
                    HashMap<String,String> hashMap=new HashMap<>();
                    hashMap.put("user_id",userBean.getUser_id());
                    hashMap.put("cart_id",ids);
                    hashMap.put("address_id",addressBean.getAddress_id());
                    hashMap.put("shipping_code",beanWuliu.getCode());
                    hashMap.put("shipping_name",beanWuliu.getName());
                    hashMap.put("shipping_price",yunfei);
                    new HttpUtils().post(ActivityOrderWrite.this, Constants.API_SUNMITORDER, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
                        @Override
                        public void success(String msg, Object json) {
                            showToast(msg);
                            Intent intent=new Intent(mContext,ActivityMyOrder.class);
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void fail(String failMsg) {
                            showToast(failMsg);
                        }
                    });
                } else {
                    //标红购物车
                }
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
            }
        });


//
    }
}
